package ru.arriah.servicedesk.web.leadExecutor.action;

import java.io.IOException;
import java.text.DateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.common.web.action.DumbAction;
import ru.arriah.servicedesk.bean.ClientBean;
import ru.arriah.servicedesk.bean.IntWrapper;
import ru.arriah.servicedesk.bean.OrganizationBean;
import ru.arriah.servicedesk.bean.RequestBean;
import ru.arriah.servicedesk.bean.RequestStatusBean;
import ru.arriah.servicedesk.ejb.RequestManagerLocalHome;
import ru.arriah.servicedesk.ejb.RequestManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.InternalException;

public class SearchRequestAction extends DumbAction {
   protected RequestManagerLocalHome requestManagerHome;

   public SearchRequestAction() throws NamingException {
      super();

      requestManagerHome =
         Utils.getRequestManagerHomeInterface();
   } 
    
   
   public String execute(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {
      try {
        int page = idVal(request.getParameter("page"));        
        int itemsPerPage = Integer.parseInt(config.getProperty("ITEMS_PER_PAGE"));
        IntWrapper records = new IntWrapper(0);
        
        RequestManagerLocalObject requestManager = 
          requestManagerHome.create();
        
        String order = request.getParameter("order");
        String orderBy = request.getParameter("orderBy");
        
        order = (order == null) ? "" : order;                
        orderBy = (orderBy == null) ? "" : orderBy;                      
        
        RequestBean requestTemplate = new RequestBean();
        RequestStatusBean requestStatusBean = new RequestStatusBean();
        requestStatusBean.setId(idVal(request.getParameter("status_query")));
        
        ClientBean clientBean = new ClientBean();
        clientBean.setFirstName(request.getParameter("client_query"));
        
        OrganizationBean organizationBean = new OrganizationBean();
        organizationBean.setFullTitle(request.getParameter("organization_query"));
        
        requestTemplate.setOrganization(organizationBean);
        requestTemplate.setClient(clientBean);
        requestTemplate.setRequestStatus(requestStatusBean);
        requestTemplate.setDispatcherText(request.getParameter("text_query"));
        requestTemplate.setClientText(request.getParameter("text_query"));
        requestTemplate.setId(idVal(request.getParameter("id_query")));
        requestTemplate.setRegNumber(request.getParameter("regnumber_query"));
        
        DateFormat dateformat = 
          DateFormat.getDateInstance(
             DateFormat.SHORT, 
             new Locale("ru")
          );
        
        try {
           requestTemplate.setSearchToRegistrationDate(
              dateformat.parse(request.getParameter("toRegistrationDate"))
           );
        } catch (Exception e) {
           requestTemplate.setSearchToRegistrationDate(
              new Date(
                 Utils.parseLongQuietly(
                    request.getParameter("toRegistrationDate")
                 )
              )
           );
        }         
         
        try {
           requestTemplate.setSearchToEndDate(
              dateformat.parse(request.getParameter("toEndDate"))
           );
        } catch (Exception e) {
           requestTemplate.setSearchToEndDate(
              new Date(Utils.parseLongQuietly(request.getParameter("toEndDate")))
           );
        }         
         
        try {
          requestTemplate.setSearchFromRegistrationDate(
             dateformat.parse(request.getParameter("fromRegistrationDate"))
          );
        } catch (Exception e) {
           requestTemplate.setSearchFromRegistrationDate(
              new Date(Utils.parseLongQuietly(request.getParameter("fromRegistrationDate")))
           ); 
        }              
         
        try {
           requestTemplate.setSearchFromEndDate(
              dateformat.parse(request.getParameter("fromEndDate"))
           );
        } catch (Exception e) {
           requestTemplate.setSearchFromEndDate(
              new Date(Utils.parseLongQuietly(request.getParameter("fromEndDate")))
           );
        }    
                        
        requestTemplate.setLeadExecutorId(
           Utils.getUserId(request)
        );
        
        Collection<RequestBean> requestsList = 
          requestManager.searchRequests(
            requestTemplate,
            orderBy, 
            order,
            page,
            itemsPerPage,
            records
          );                     
        
        Collection<RequestStatusBean> statusList = 
           requestManager.selectRequestStatuses();

        requestManager.remove();        
                                      
        this.pageNavigationToRequest(
          page,          
          records.getValue(), 
          "leadexecutorui?_action=search" +
          "&status_query=" + request.getParameter("status_query") +
          "&client_query=" + request.getParameter("client_query") +
          "&organization_query=" + request.getParameter("organization_query") +
          "&text_query=" + request.getParameter("text_query") +
          "&id_query=" + request.getParameter("id_query") +
          "&regnumber_query=" + request.getParameter("regnumber_query") +
          "&fromRegistrationDate=" + requestTemplate.getSearchFromRegistrationDate().getTime() +
          "&toRegistrationDate=" + requestTemplate.getSearchToRegistrationDate().getTime() +
          "&fromEndDate=" +  requestTemplate.getSearchFromEndDate().getTime() +
          "&toEndDate=" + requestTemplate.getSearchToEndDate().getTime() +
          "&orderBy="+orderBy+"&order="+order+"&page=",
          request
        );
        
        
        request.setAttribute("fromRegistrationDate", requestTemplate.getSearchFromRegistrationDate());
        request.setAttribute("toRegistrationDate", requestTemplate.getSearchToRegistrationDate());
        request.setAttribute("fromEndDate", requestTemplate.getSearchFromEndDate());
        request.setAttribute("toEndDate", requestTemplate.getSearchToEndDate());
        
        request.setAttribute("action", "search");
        request.setAttribute("statusList", statusList); 
        request.setAttribute("requestsList", requestsList);               
        request.setAttribute("order", (order.equals("ASC") ? "DESC" : "ASC")); 
        request.setAttribute(
          "searchAttributes",
          "&status_query=" + request.getParameter("status_query") +
          "&client_query=" + request.getParameter("client_query") +
          "&organization_query=" + request.getParameter("organization_query") +
          "&text_query=" + request.getParameter("text_query") +
          "&id_query=" + request.getParameter("id_query") +
          "&regnumber_query=" + request.getParameter("regnumber_query") +
          "&fromRegistrationDate=" + requestTemplate.getSearchFromRegistrationDate().getTime() +
          "&toRegistrationDate=" + requestTemplate.getSearchToRegistrationDate().getTime() +
          "&fromEndDate=" +  requestTemplate.getSearchFromEndDate().getTime() +
          "&toEndDate=" + requestTemplate.getSearchToEndDate().getTime()
        );
        return actionMapping.getSuccessTarget();
      } catch (Exception e) {
         handleException(e, "execute");
         throw new InternalException("ErrorMessage.internal");
      }
   }
}
